﻿// 中文字两个字节    
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {    
  var length = value.length;    
  for(var i = 0; i < value.length; i++){    
   if(value.charCodeAt(i) > 127){    
    length++;    
   }     
  }    
  return this.optional(element) || ( length >= param[0] && length <= param[1] );    
}, "用户名在3-20个字节之间(一个中文2个字节)");
jQuery.validator.addMethod("confirmWith", function(value, element, param) {
    var result = false;    
    var p = $('#' + param);
    if (p) {        
        result = (p.val() == value);
    }
    return result;
}, "两次密码输入不一致");

$(document).ready(function() {
    $("#form_register").validate(
        {
            rules: {
                username: {
                    required: true,
                    byteRangeLength: [3, 20],
                    remote: _URL_VALIDATE_USERNAME
                },
                password: {
                    required: true,
                    minlength: 6
                },
                confirmPassword: {
                    required: true,
                    confirmWith: "password"
                },
                email: {
                    required: true,
                    email: true,
                    remote: _URL_VALIDATE_EMAIL
                },
                captcha: {
                    required:true
                }
            },
            messages: {
                email: {
                    required: "Email不能空",
                    email: "请输入有效的Email地址",
                    remote: jQuery.format("{0}已被使用")

                },
                username: {
                    required: "请输入您要使用的用户名",
                    remote: jQuery.format("{0}已被注册")
                },
                password: {
                    required: "请输入密码",
                    minlength: "密码最少6位"
                },
                confirmPassword: {
                    required: "请重复输入一遍上面输入的密码"
                },
                captcha: {
                    required: "请输入验证码"
                }

            },
            success: function(label) {
                // set &nbsp; as text for IE
                label.html("&nbsp;").addClass("checked");
            }
        });
    initcaptcha();
    $("#username").focus();
    $("#captcha").blur(function() {
        $('#div_captcha').hide();
        $("#img_captcha").attr('src', _IMG_CAPTCHA + "?" + Math.random());
    });
    $("#captcha").focus(function() { $('#div_captcha').fadeIn(); });

});

function initcaptcha() {
    var div = $('<div id="div_captcha"></div>');
    var img = $('<img id="img_captcha" src="' + _IMG_CAPTCHA + '" alt="captcha"/>');
    var captcha = $('#captcha');
    var offset = captcha.offset();   
    div.css("left", offset.left + captcha.width() + 5+ "px");
    div.css("top", offset.top - 60 + "px");
    div.append(img);
    $("body").append(div);
    
}